package gov.pbc.nn.kjgl.maintenance.handler;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonJdbcDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.service.IDeptService;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.AssignmentHandler;
import com.bstek.uflo.process.node.TaskNode;

/**
 * 系统业务主管部门负责人（南宁是处长，地市是科长）
 * 
 * @author Administrator
 * 
 */
@Component(SysBusinessDeptLeaderAssignmentHandler.BEAN_ID)
public class SysBusinessDeptLeaderAssignmentHandler implements AssignmentHandler {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.handler.SysBusinessDeptLeaderAssignmentHandler";

	@Resource(name = CommonJdbcDao.BEAN_ID)
	private CommonJdbcDao jdbcDao;

	@Resource(name = IDeptService.BEAN_ID)
	private IDeptService ds;

	@Override
	public Collection<String> handle(TaskNode node, ProcessInstance pi, Context context) {
		List<String> users = new ArrayList<String>();
		String businessDeptLeader = (String) context.getProcessService().getProcessVariable("businessDeptLeader", pi);
		if (StringUtils.isNotBlank(businessDeptLeader)) {
			users.add(businessDeptLeader);
		} else {
			String sysId = (String) context.getProcessService().getProcessVariable("sysId", pi);
			List<IUser> userList = this.getBusinessDeptLeader(sysId);
			for (IUser user : userList) {
				users.add(user.getUsername());
			}
		}
		return users;
	}

	public List<IUser> getBusinessDeptLeader(String sysId) {
		String sql = "select s.DEPT_ID_ from t_sys_entity s where s.ID_=?";
		String deptId = this.jdbcDao.getJdbcTemplate().queryForObject(sql, new Object[] { sysId }, String.class);
		Dept businessDept = (Dept) ((Dept) ds.loadDeptById(deptId)).getCDept();
		List<IUser> userList = null;
		if (StringUtils.startsWith(businessDept.getId(), Dept.NANNING)) {
			// 南宁
			userList = SecurityUtils.getUserByRoleForDeptWithChildren(businessDept.getId(), Constants.ROLE_CZ);
		} else {
			userList = SecurityUtils.getUserByRoleForDeptWithChildren(businessDept.getId(), Constants.ROLE_KZ);
		}
		return userList;
	}

}
